import { ref, computed } from 'vue'
import { isUserLoggedIn, getUserToken, getUserId, redirectToLogin } from '../utils/auth'

/**
 * 用户认证状态管理组合式函数
 */
export function useAuth() {
  // 响应式的登录状态
  const isLoggedIn = ref(isUserLoggedIn())
  
  // 计算属性
  const userToken = computed(() => getUserToken())
  const userId = computed(() => getUserId())
  
  // 检查登录状态
  const checkAuth = () => {
    isLoggedIn.value = isUserLoggedIn()
    return isLoggedIn.value
  }
  
  //主要在组件中使用这个就可以了
  // 要求登录，如果未登录则跳转
  const requireAuth = () => {
    if (!checkAuth()) {
      redirectToLogin()
      return false
    }
    return true
  }
  
  // 登出
  const logout = () => {
    redirectToLogin()
    isLoggedIn.value = false
  }
  
  return {
    isLoggedIn,
    userToken,
    userId,
    checkAuth,
    requireAuth,
    logout
  }
}
